<template>
  <div class="parameter-list-container">
    <label class="input-label">{{ label }}</label>
    <div class="parameter-list">
      <div
          v-for="(para, index) in modelValue"
          :key="index"
          class="parameter-item"
          @mouseenter="handleMouseEnter($event)"
          @mouseleave="handleMouseLeave($event)"
      >
        <span class="parameter-text">{{ typeof para === 'string' ? para : para.name }}</span>
        <span
            class="setting-icon"
            @click="showSettingDialog(index)"
        >⚙️</span>
        <span
            class="remove-icon"
            @click="removeParameter(index)"
        >-</span>
      </div>
      <div class="parameter-item add-item" @click="showAddParameterDialog">
        <span class="add-icon">+</span>
      </div>
    </div>

    <!-- 添加参数对话框 -->
    <div v-if="showAddDialog" class="dialog-overlay" @click="showAddDialog = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>添加{{ label }}</h3>
        </div>
        <div class="dialog-body">
          <select v-model="selectedNewPara" class="input-select" style="width: 100%;">
            <option value="" disabled selected>请选择参数</option>
            <option
                v-for="para in availableParameters"
                :key="typeof para === 'string' ? para : para.name"
                :value="typeof para === 'string' ? para : para.name"
            >
              {{ typeof para === 'string' ? para : para.name }}
            </option>
          </select>
        </div>
        <div class="dialog-footer">
          <button @click="showAddDialog = false" class="action-button">取消</button>
          <button @click="addNewParameter" class="action-button" :disabled="!selectedNewPara">添加</button>
        </div>
      </div>
    </div>

    <!-- 参数设置对话框 -->
    <div v-if="showSettingDialogFlag" class="dialog-overlay" @click="showSettingDialogFlag = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>设置参数</h3>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>参数名称:</label>
            <input
              v-model="editingParameter.name"
              class="input-field"
              :disabled="!isCreating"
            />
          </div>

          <div
            v-for="(value, key) in currentParameterDefinition"
            :key="key"
            class="form-group"
            v-show="key !== 'name'"
          >
            <label>{{ key }}:</label>
            <select
              v-if="Array.isArray(value)"
              v-model="editingParameter[key]"
              class="input-select"
            >
              <option value="">请选择</option>
              <option
                v-for="option in value"
                :key="option"
                :value="option"
              >
                {{ option }}
              </option>
            </select>
            <input
              v-else
              v-model="editingParameter[key]"
              class="input-field"
              :placeholder="String(value)"
            />
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="showSettingDialogFlag = false" class="action-button">取消</button>
          <button @click="saveParameterSettings" class="action-button">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, reactive} from 'vue'

interface ParameterDefinition {
  name: string;
  [key: string]: any;
}

interface ParameterInstance {
  name: string;
  [key: string]: any;
}

interface Props {
  modelValue: (string | ParameterInstance)[]
  label: string
  allParameters: ParameterDefinition[]
}

interface Emits {
  (e: 'update:modelValue', value: (string | ParameterInstance)[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 对话框相关状态
const showAddDialog = ref(false)
const showSettingDialogFlag = ref(false)
const selectedNewPara = ref("")
const editingParameterIndex = ref(-1)
const isCreating = ref(false)

// 正在编辑的参数
const editingParameter = reactive<ParameterInstance>({
  name: ''
})

// 当前参数定义（用于设置对话框）
const currentParameterDefinition = computed(() => {
  if (selectedNewPara.value) {
    const paramDef = props.allParameters.find(p =>
      (typeof p === 'string' ? p : p.name) === selectedNewPara.value
    );
    return paramDef || { name: selectedNewPara.value };
  }
  return { name: '' };
})

// 计算还可以添加的参数（未被选择的参数）
const availableParameters = computed(() => {
  return props.allParameters.filter(p => {
    const paramName = typeof p === 'string' ? p : p.name;
    return !props.modelValue.some(item => {
      const itemName = typeof item === 'string' ? item : item.name;
      return itemName === paramName;
    });
  });
})

// 显示添加参数对话框
const showAddParameterDialog = () => {
  selectedNewPara.value = ""
  showAddDialog.value = true
}

// 添加新参数
const addNewParameter = () => {
  if (selectedNewPara.value) {
    const isSelected = props.modelValue.some(item => {
      const itemName = typeof item === 'string' ? item : item.name;
      return itemName === selectedNewPara.value;
    });

    if (!isSelected) {
      // 查找参数的完整信息
      const paramInfo = props.allParameters.find(p => {
        const paramName = typeof p === 'string' ? p : p.name;
        return paramName === selectedNewPara.value;
      });

      const newValue = [...props.modelValue];
      if (typeof paramInfo === 'object' && paramInfo !== null) {
        // 如果参数有详细信息，则添加完整对象
        newValue.push({...paramInfo});
      } else {
        // 否则只添加名称
        newValue.push(selectedNewPara.value);
      }
      emit('update:modelValue', newValue);
    }
  }
  showAddDialog.value = false
}

// 删除参数
const removeParameter = (index: number) => {
  const newValue = [...props.modelValue]
  newValue.splice(index, 1)
  emit('update:modelValue', newValue)
}

// 显示参数设置对话框
const showSettingDialog = (index: number) => {
  editingParameterIndex.value = index
  const param = props.modelValue[index]

  // 清空之前的编辑数据
  Object.keys(editingParameter).forEach(key => {
    delete editingParameter[key];
  });

  if (typeof param === 'string') {
    editingParameter.name = param;
    // 获取参数定义并设置默认值
    const paramDef = props.allParameters.find(p =>
      (typeof p === 'string' ? p : p.name) === param
    );
    if (paramDef) {
      Object.keys(paramDef).forEach(key => {
        // 如果属性是数组且有值，则默认选择第一个
        if (Array.isArray(paramDef[key]) && paramDef[key].length > 0) {
          editingParameter[key] = paramDef[key][0];
        } else {
          editingParameter[key] = paramDef[key];
        }
      });
    } else {
      editingParameter.name = param;
    }
  } else {
    // 复制参数的所有属性
    Object.keys(param).forEach(key => {
      editingParameter[key] = param[key];
    });
  }

  // 设置当前选中的参数名
  selectedNewPara.value = editingParameter.name;
  isCreating.value = false
  showSettingDialogFlag.value = true
}

// 保存参数设置
const saveParameterSettings = () => {
  const newValue = [...props.modelValue]

  // 构建参数对象
  const paramObject: ParameterInstance = {...editingParameter};

  if (isCreating.value) {
    newValue.push(paramObject)
  } else {
    newValue[editingParameterIndex.value] = paramObject
  }

  emit('update:modelValue', newValue)
  showSettingDialogFlag.value = false
}

// 处理鼠标进入事件
const handleMouseEnter = (event: MouseEvent) => {
  const target = event.currentTarget as HTMLElement;
  target.classList.add('hover');
};

// 处理鼠标离开事件
const handleMouseLeave = (event: MouseEvent) => {
  const target = event.currentTarget as HTMLElement;
  target.classList.remove('hover');
};

</script>

<style scoped>
.parameter-list-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
  background-color: #f9f9f9; /* 添加淡色背景 */
  padding: 12px; /* 添加内边距 */
  border-radius: 6px; /* 添加圆角 */
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); /* 添加轻微阴影 */
  border: 1px solid #eeeeee; /* 添加轻微边框 */
}

.input-label {
  font-weight: bold;
  color: #333;
  min-width: 120px;
}

.parameter-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 5px;
}

.parameter-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 4px 8px;
  background-color: #e1efff;
  border-radius: 4px;
  font-size: 13px;
  cursor: default;
}

.parameter-item.hover {
  background-color: #d0e5ff;
}

.parameter-text {
  margin-right: 6px;
}

.setting-icon {
  display: none;
  position: absolute;
  top: -8px;
  left: -8px;
  width: 16px;
  height: 16px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  text-align: center;
  line-height: 16px;
  cursor: pointer;
}

.remove-icon {
  display: none;
  position: absolute;
  top: -8px;
  right: -8px;
  width: 16px;
  height: 16px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  text-align: center;
  line-height: 16px;
  cursor: pointer;
}

.parameter-item.hover .setting-icon,
.parameter-item.hover .remove-icon {
  display: block;
}

.add-item {
  background-color: #f0f0f0;
  cursor: pointer;
}

.add-icon {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 80vh;
  overflow-y: auto;
}

.dialog-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
}

.dialog-body {
  padding: 16px;
}

.dialog-footer {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #eee;
}

.input-select,
.input-field {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  width: 100%;
  box-sizing: border-box;
}

.input-field:focus {
  outline: none;
  border-color: #409eff;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.action-button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.action-button:hover {
  background-color: #66b1ff;
}

.action-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
